<template>
  <div>
    <form action="/">
      <van-search v-model="keyword" placeholder="请输入搜索关键词" @search="onSearch" @clear="onClear" />
    </form>
    <div class="container">
      <van-sidebar class="aside" v-model="activeKey">
        <van-sidebar-item title="全部" @click="getAll()" />
        <van-sidebar-item title="新品推荐" @click="get_dish_type(1)" />
        <van-sidebar-item title="销量霸榜" @click="get_dish_type(2)" />
        <van-sidebar-item title="用户好评" @click="get_dish_type(3)" />
        <van-sidebar-item v-for="item in cuisine_list" :key="item.id" :title="item.name" @click="get_dish_cuisine(item.id)" />
      </van-sidebar>
      <main>
        <van-list class="dishList" :offset="0" v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :immediate-check="false">
          <span class="cuisine_describe van-multi-ellipsis--l2" v-if="activeKey == 0">酸甜苦辣，一应俱全，任君挑选。</span>
          <span class="cuisine_describe van-multi-ellipsis--l2" v-if="activeKey == 1">本店新品，推荐尝试。</span>
          <span class="cuisine_describe van-multi-ellipsis--l2" v-if="activeKey == 2">好不好吃，看销量，用户说了算。</span>
          <span class="cuisine_describe van-multi-ellipsis--l2" v-if="activeKey == 3">精挑细选，用户评价极高,值得一试。</span>
          <span class="cuisine_describe van-multi-ellipsis--l2" v-if="activeKey >= 4">{{ cuisine_list[activeKey - 4].describe }}</span>
          <van-divider />
          <van-card v-for="item in dish_list" :tag="item.type == 1 ? '新品推荐' : item.type == 2 ? '销量霸榜' : item.type == 3 ? '用户好评' : ''" :key="item.id" :price="item.price" :desc="item.describe" :title="item.name" :thumb="'http://8.138.102.145/images/' + item.img">
            <template #tags>
              <van-tag plain type="danger" v-for="i in item.itemList" :key="i.id">{{ i.name }}</van-tag>
            </template>
            <template #footer>
              <div @click="add_cart(item)">
                <v-icon name="io-add-circle-sharp" fill="#e84b3c"></v-icon>
              </div>
            </template>
          </van-card>
          <van-empty v-if="!dish_list.length" image="search" description="该菜系下没有菜品" />
        </van-list>
      </main>
      <van-sku ref="sku" v-model="show" :sku="sku" :goods="goods" :goods-id="goodsId" :hide-stock="sku.hide_stock" @buy-clicked="onBuyClicked" @add-cart="onAddCartClicked" @stepper-change="stepperChange" @sku-selected="skuSelected" reset-stepper-on-hide reset-selected-sku-on-hide>
        <template #sku-header-price="sku">
          <div class="van-sku__goods-price">
            <span class="van-sku__price-symbol">￥</span><span class="van-sku__price-num" v-if="select_price_num.totalPrice !== 0">{{ select_price_num.totalPrice }}</span>
            <span class="van-sku__price-num" v-else>{{ sku.price }}</span>
          </div>
        </template>
        <template #sku-actions-top>
          <van-cell title="描述" :label="goods.describe" />
        </template>
      </van-sku>
    </div>
  </div>
</template>

<script>
export default {
  mounted() {
    this.get_cuisine_list();
    this.get_dish_list();
  },
  data() {
    return {
      activeKey: 0, //菜系列表编号
      cuisine_list: [],
      dish_list: [],
      // sku
      show: false,
      sku: {
        // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
        // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
        tree: [
          {
            k: '口味', // skuKeyName：规格类目名称
            k_s: 's1', // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
            v: [
              // {
              //   id: "1", // skuValueId：规格值 id
              //   name: "不辣", // skuValueName：规格值名称
              // },
              // {
              //   id: "2",
              //   name: "麻辣",
              // },
            ],
          },
        ],
        // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
        list: [
          // {
          //   id: 0, // skuId
          //   s1: "1", // 规格类目 k_s 为 s1 的对应规格值 id
          //   price: 100, // 价格（单位分）
          //   stock_num: 999, // 当前 sku 组合对应的库存
          // },
          // {
          //   id: 1, // skuId
          //   s1: "2", // 规格类目 k_s 为 s1 的对应规格值 id
          //   price: 100, // 价格（单位分）
          //   stock_num: 999, // 当前 sku 组合对应的库存
          // },
        ],
        price: '', // 默认价格（单位元）
        collection_id: 0, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        none_sku: false, // 是否无规格商品
        stock_num: 999,
        // messages: [
        //   {
        //     // 商品留言
        //     datetime: "0", // 留言类型为 time 时，是否含日期。'1' 表示包含
        //     multiple: "0", // 留言类型为 text 时，是否多行文本。'1' 表示多行
        //     name: "备注", // 留言名称
        //     type: "text", // 留言类型，可选: id_no（身份证）, text, tel, date, time, email
        //     required: "0", // 是否必填 '1' 表示必填
        //     placeholder: "请填写你的要求", // 可选值，占位文本
        //     extraDesc: "", // 可选值，附加描述文案
        //   },
        // ],
        hide_stock: true, // 是否隐藏剩余库存
      },
      goods: {
        picture: '',
        describe: '',
      },
      goodsId: '',
      select_price_num: {
        price: 0,
        num: 1,
        totalPrice: 0,
      },

      keyword: '', //搜索关键字
      loading: false, //是否加载
      finished: false, //是否完成
      queryParams: {
        name: '', //菜品名称
        pageSize: 10, //每页条数
        pageNum: 1,
        cuisineId: null, //菜系编号
        type: null, //类型
      }, //查询参数
      totalRow: 0,
    };
  },
  watch: {
    show(newVal) {
      if (!newVal) {
        this.select_price_num.totalPrice = 0;
      }
    },
  },
  methods: {
    //搜索
    onSearch(val) {
      this.queryParams.pageNum = 1;
      this.queryParams.cuisineId = null;
      this.queryParams.type = null;
      this.finished = false;
      this.activeKey = 0;
      this.queryParams.name = val;
      this.get_dish_list();
    },
    //清除
    onClear() {
      this.queryParams.pageNum = 1;
      this.queryParams.cuisineId = null;
      this.queryParams.type = null;
      this.finished = false;
      this.activeKey = 0;
      this.queryParams.name = '';
      this.get_dish_list();
    },
    //获取菜系列表
    get_cuisine_list() {
      this.req.get('/cuisine').then((res) => {
        this.cuisine_list = res.rows;
      });
    },
    //获取菜品列表
    get_dish_list() {
      let params = this.queryParams;
      this.req.get('/dish', { params }).then((res) => {
        this.dish_list = res.rows;
        this.totalRow = res.totalRow;
        if (this.dish_list.length >= this.totalRow) {
          this.finished = true;
        }
      });
    },
    //点击添加购物车
    add_cart(item) {
      this.show = true;
      this.goods.picture = 'http://8.138.102.145/images/' + item.img;
      this.goods.describe = item.describe;
      if (item.itemList.length) {
        this.sku.tree[0] = {
          k: '口味',
          k_s: 's1',
          v: item.itemList.map((v) => {
            return { id: v.id, name: v.name };
          }),
        };
        this.sku.list = item.itemList.map((v) => {
          return {
            id: v.id,
            name: v.name,
            s1: v.id,
            price: (item.price + v.price) * 100,
            stock_num: 999,
          };
        });
      } else {
        this.sku.tree[0] = {
          k: '口味',
          k_s: 's1',
          v: [{ id: 0, name: '无' }],
        };
        this.sku.list = [
          {
            id: 0,
            s1: 0,
            price: item.price * 100,
            stock_num: 999,
          },
        ];
      }
      this.sku.price = item.price;
      this.goodsId = item.id;
    },
    //点击购买
    onBuyClicked(val) {
      console.log(val);
      let result = {
        dishId: val.goodsId,
        price: val.selectedSkuComb.price / 100,
        quantity: val.selectedNum,
        status: 0,
        tasteId: val.selectedSkuComb.id,
      };
      this.show = false;
      this.$router.push({
        path: '/pay',
        query: {
          list: JSON.stringify(result),
        },
      });
    },
    //点击加入购物车
    onAddCartClicked(val) {
      let result = {
        dishId: val.goodsId,
        price: val.selectedSkuComb.price / 100,
        quantity: val.selectedNum,
        status: 0,
        tasteId: val.selectedSkuComb.id,
        type: 0,
      };
      this.req.post('/cart', result);
      this.show = false;
      this.$notify({
        type: 'success',
        message: '加入购物车成功',
      });
    },
    stepperChange(val) {
      this.select_price_num.num = val;
      // this.sku.list.forEach((v) => {
      //   v.price = this.select_price_num.num * this.select_price_num.price * 100;
      // });
      // this.sku.price = this.select_price_num.num * this.select_price_num.price;
      this.select_price_num.totalPrice = this.select_price_num.num * this.select_price_num.price;
      console.log(this.sku.price);
    },
    skuSelected(val) {
      console.log(val);
      if (!val.selectedSkuComb) {
        this.select_price_num.price = 0;
      } else {
        this.select_price_num.price = val.selectedSkuComb.price / 100;
      }
      this.select_price_num.totalPrice = this.select_price_num.num * this.select_price_num.price;
      console.log(this.sku.price);
    },
    //新品推荐、销量霸榜、用户好评等模块
    get_dish_type(type) {
      this.queryParams.pageNum = 1;
      this.finished = false;
      this.queryParams.type = type;
      this.queryParams.cuisineId = null;
      this.queryParams.pageSize = 10;
      this.get_dish_list();
    },
    //选择菜系
    get_dish_cuisine(cuisineId) {
      this.queryParams.pageNum = 1;
      this.finished = false;
      this.queryParams.type = null;
      this.queryParams.cuisineId = cuisineId;
      this.queryParams.pageSize = 10;
      this.get_dish_list();
    },
    //获取全部
    getAll() {
      this.queryParams.pageNum = 1;
      this.finished = false;
      this.queryParams.cuisineId = null;
      this.queryParams.pageSize = 10;
      this.queryParams.type = null;
      this.queryParams.name = '';
      this.get_dish_list();
    },
    //下拉刷新
    onLoad() {
      this.loading = true;
      if (this.totalRow <= this.dish_list.length) this.finished = true;
      this.queryParams.pageNum = this.queryParams.pageNum + 1;
      this.req.get('/dish', { params: this.queryParams }).then((res) => {
        this.dish_list = this.dish_list.concat(res.rows);
        console.log('触发下拉刷新', this.dish_list.length, this.queryParams.pageSize);
        this.loading = false;
        if (this.dish_list.length >= this.totalRow) {
          this.finished = true;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  height: calc(100vh - 50px);
  display: flex;

  .aside {
    width: 6.25rem;
    background-color: #f7f8fa;
  }
  main {
    flex: 1;
    padding: 0.625rem;
    background-color: #fff;
    overflow: scroll;
    .dishList {
      padding-bottom: 30px;
      .cuisine_describe {
        color: #777;
      }
    }
  }
}
</style>
